/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.urge.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.SMSUtils;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.vo.ZfAndManageUserInfoVO;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.HandleAdjustCaseInfoPageRequest;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStatusEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseHandlePersonRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseHandlePersonRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseHandlePersonAdjustInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.TaskVo;
import com.icinfo.cloud.provider.punish.ucase.urge.dto.CaseUrgeAddDto;
import com.icinfo.cloud.provider.punish.ucase.urge.dto.CaseUrgeDetailDto;
import com.icinfo.cloud.provider.punish.ucase.urge.dto.CaseUrgePageRequest;
import com.icinfo.cloud.provider.punish.ucase.urge.dto.CaseUrgePageResponse;
import com.icinfo.cloud.provider.punish.ucase.urge.mapper.CaseUrgeHisMapper;
import com.icinfo.cloud.provider.punish.ucase.urge.model.CaseUrgeHis;
import com.icinfo.cloud.provider.punish.ucase.urge.service.ICaseUrgeHisService;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.icinfo.framework.tools.utils.BeanUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.annotations.Case;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述: 案件催办记录 case_urge_his 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年11月21日
 */
@Service
public class CaseUrgeHisServiceImpl extends MyBatisServiceSupport implements ICaseUrgeHisService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseUrgeHisServiceImpl.class);

    @Resource
    private CaseUrgeHisMapper caseUrgeHisMapper;

    @Resource
    private ICaseHandlePersonAdjustInfoService caseHandlePersonAdjustInfoService;

    @Resource
    private CaseHandlePersonRecordMapper caseHandlePersonRecordMapper;

    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;

    @Value("${ding.sendUrl}")
    private String dingSendUrl;

    /**
     * 查询案件催办页面
     * @param request
     * @return
     */
    @Override
    public List<CaseUrgePageResponse> caseUrgePage(CaseUrgePageRequest request) {
        UserDTO userDTO= UserUtil.getUserInfo();
        if (ObjectUtil.isEmpty(userDTO)){
            throw new RuntimeException("用户信息获取失败");
        }
        String deptType=userDTO.getDeptType();
        if(Constant.STRING_2.equals(deptType)){
            request.setCaseDeptCode(userDTO.getDeptCode());
        }
        request.setCaseOrgCode(userDTO.getOrgCode());
        //根据casePartyType组装参数
        getPartyTypeParam(request);
        PageHelper.startPage(request.getPageNum(),request.getLength());
        List<CaseUrgePageResponse> list = caseUrgeHisMapper.selectCaseUrgePage(request);
        if (CollectionUtils.isNotEmpty(list)){
            for (CaseUrgePageResponse vo : list) {
                vo.setCaseStatusName(CaseStatusEnum.getValueByCode(vo.getCaseStatus()));
                //查询承办人
                String caseId = vo.getCaseId();
                //1.循环设置处理人员
                Example example = new Example(CaseHandlePersonRecord.class);
                example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status",Constant.STRING_1);
                example.orderBy("handlePersonType").asc();
                List<CaseHandlePersonRecord> handlePersonRecords = caseHandlePersonRecordMapper.selectByExample(example);
                String handPersonName = handlePersonRecords.stream().map(p -> p.getHandlePersonName()).collect(Collectors.joining(","));
                vo.setCaseHandleName(handPersonName);
                String partyName = caseHandlePersonAdjustInfoService.getPartyName(vo.getCaseId());
                vo.setPartyName(partyName);
                //2.计算剩余时间
                vo.setTimeColor("");
                if( vo.getCaseTimeLimit()!=null && vo.getCaseVerdictEndTime()==null){
                    int timeLimit = BaseUtil.getBetweenDays(BaseUtil.getTodayStartDate(), vo.getCaseTimeLimit());
                    handleRemainTimes(timeLimit, vo);
                    //3.红橙黄绿蓝
                    //分红（当前日期-办案期限<0)、黄(当前日期-办案期限<=7)、蓝色(当前日期-办案期限>7) 2022-10-12
                    if (timeLimit < Constant.INTEGER_0) {
                        vo.setTimeColor("red");
                    } else if (timeLimit <= Constant.INTEGER_7) {
                        vo.setTimeColor("yellow");
                    } else if (timeLimit > Constant.INTEGER_7) {
                        vo.setTimeColor("blue");
                    }
                    //暂停设置为灰色
                    if (CaseStatusEnum.SUSPEND.getCode().equals(vo.getCaseStatus())) {
                        vo.setTimeColor("gray");
                    }
                }
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addCaseUrge(CaseUrgeAddDto dto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtil.isEmpty(userInfo)){
            logger.info("===查询案件催办页面=>用户信息获取失败===");
            throw new RuntimeException("用户信息获取失败");
        }
        CaseUrgeHis caseUrgeHis = CaseUrgeHis
                .builder()
                .id(StringUtils.uuid())
                .caseId(dto.getCaseId())
                .urgeContent(dto.getUrgeContent())
                .createUserName(userInfo.getRealName())
                .createUserId(userInfo.getUserId().toString())
                .createTime(new Date())
                .build();
        if (caseUrgeHisMapper.insertSelective(caseUrgeHis) > 0){
            //通知对应人员
            Example example = new Example(CaseHandlePersonRecord.class);
            example.createCriteria().andEqualTo("caseId", dto.getCaseId()).andEqualTo("status",Constant.STRING_1);
            example.orderBy("handlePersonType").asc();
            List<ZfAndManageUserInfoVO> zfAndManageUserInfoVoList = xzzfInterfaceService.getZfAndManageUsersByUserIds(
                    caseHandlePersonRecordMapper.selectByExample(example)
                    .stream().map(CaseHandlePersonRecord::getHandlePersonId).collect(Collectors.toList())
            );
            if (CollectionUtils.isNotEmpty(zfAndManageUserInfoVoList) && zfAndManageUserInfoVoList.size() > 0){
                for (ZfAndManageUserInfoVO user : zfAndManageUserInfoVoList) {
                    try {
                        // 发送ding消息
                        if(org.apache.commons.lang.StringUtils.isNotEmpty(user.getZwdingAccountId())){
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("dingDingId", user.getZwdingAccountId());
                            jsonObject.put("caseNumber",dto.getUrgeContent());
                            jsonObject.put("dingMsgType","caseUrge");
                            BaseUtil.post(dingSendUrl, jsonObject);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return 1;
        }else {
            return 0;
        }
    }

    @Override
    public List<CaseUrgeDetailDto> getCaseUrgeDetail(String caseId) {
        Example example = new Example(CaseUrgeHis.class);
        example.createCriteria()
                .andEqualTo("caseId", caseId);
        example.orderBy("createTime").asc();
        List<CaseUrgeHis> caseUrgeHis = caseUrgeHisMapper.selectByExample(example);
        List<CaseUrgeDetailDto> caseUrgeDetailDtoList = null;
        if (CollectionUtils.isNotEmpty(caseUrgeHis)){
            caseUrgeDetailDtoList = new ArrayList<>();
            for (CaseUrgeHis caseUrgeHi : caseUrgeHis) {
                caseUrgeDetailDtoList.add(CaseUrgeDetailDto.builder().urgeContent(caseUrgeHi.getUrgeContent()).createTime(caseUrgeHi.getCreateTime()).build());
            }
        }
        return caseUrgeDetailDtoList;
    }

    private void getPartyTypeParam(CaseUrgePageRequest request) {
        if(Constant.STRING_1.equals(request.getCasePartyType())){
            //个人 类型大类为 1  类型小类 1
            request.setCasePartyBigType(Constant.STRING_1);
            request.setCasePartyType(Constant.STRING_1);
        }else if(Constant.STRING_2.equals(request.getCasePartyType())){
            //法人 类型大类为 2  类型小类 1
            request.setCasePartyBigType(Constant.STRING_2);
            request.setCasePartyType(Constant.STRING_1);
        }else if(Constant.STRING_3.equals(request.getCasePartyType())){
            //个体工商户 类型大类为 2  类型小类 2
            request.setCasePartyBigType(Constant.STRING_2);
            request.setCasePartyType(Constant.STRING_2);
        }else if(Constant.STRING_4.equals(request.getCasePartyType())){
            //其他组织 类型大类为 2  类型小类 2
            request.setCasePartyBigType(Constant.STRING_2);
            request.setCasePartyType(Constant.STRING_3);

        }
    }

    /**
     * 计算超出时间--办案日期，裁决完毕日期
     *
     * @param timeLimit
     * @param vo
     * @return void
     * @author lxj
     * @date 2022/3/1
     **/
    private void handleRemainTimes(int timeLimit, CaseUrgePageResponse vo) {
        //办案期限
        if (timeLimit == Constant.INTEGER_0) {
            //vo.setRemainTime("已到期");
            vo.setRemainTime("截止日");
        } else if (timeLimit > Constant.INTEGER_0) {
            vo.setRemainTime("剩余" + timeLimit + "天");
        } else {
            vo.setRemainTime("超" + String.valueOf(timeLimit).substring(Constant.INTEGER_1) + "天");
        }

        if (CaseStatusEnum.SUSPEND.getCode().equals(vo.getCaseStatus())) {
            vo.setRemainTime("暂停");
        }

        if (vo.getCaseVerdictEndTime() == null) {
            return;
        }
        //裁决期限
        int verdictLimit = BaseUtil.getBetweenDays(BaseUtil.getTodayStartDate(), vo.getCaseVerdictEndTime());
        if (verdictLimit == Constant.INTEGER_0) {
            vo.setRemainVerdictTime("已到期");
        } else if (verdictLimit > Constant.INTEGER_0) {
            vo.setRemainVerdictTime("剩余" + verdictLimit + "天");
        } else {
            vo.setRemainVerdictTime("超" + String.valueOf(verdictLimit).substring(Constant.INTEGER_1) + "天");
        }

    }
}
